<?php

class dbt_user extends sing_table {

    function openids2detail($openids){
        if(!$openids){
            return array();
        }
        return DB::fetch_all("select * from %t where openid in (%n)",array('wx_wxuser',$openids),'openid');
    }
    public function get($memberid, $mid='') {
//        $r = memory('get' , $openid.'-usr-'.$mid);
       // if(!$r){
        DB::SetMainDB(DB_MAIN);
        $r = DB::fetch_first('select id,name from %t where member_id=%d and mid=%s limit 1', array('common_member_perfect', $memberid, $mid));
       //     memory('set' , $openid.'-usr-'.$mid ,$r);
       // }
        return $r;
    }

    //读取用户信息
    public function member_info( $memberid,$mid ) {
        DB::SetMainDB(DB_MAIN);
        $r = DB::fetch_first('select id,nickname,account,password,password_rand from %t where id=%d and mid=%s limit 1', array('common_member', $memberid, $mid));
        return $r;
    }

    //所有用户组
    function get_group($_mid)
    {
        DB::setRead();
        return DB::fetch_all('select * from %t where mid=%s and status=1 and display=1', array('wx_group', $_mid));
    }

    //验证权限
    function is_refund($_mid)
    {
        $authority = DB::fetch_first('select id from %t where member_id=%d and member_grant=1',array('common_member_grant',$_mid));

        return $authority;
    }

    public function getuser($openid,$mid)
    {
        DB::SetMainDB(DB_MAIN);
        $r = DB::fetch_first('select * from %t where openid=%s and mid=%s', array('wx_wxuser', $openid, $mid));
        return $r;
    }

	public function getGroupM($mid,$id,$upmemory = 0) {
        if(!$mid || !$id) return false;
		if(!$upmemory) $r = memory('get','wx-group-'.$mid.'-'.$id);
		if (!$r) {
			$r = DB::fetch_first('select * from %t where mid=%s and id=%d', array('wx_group', $mid, $id));
			if($r) memory('set','es-group-'.$mid.'-'.$id,$r);
		}
		return $r;
    }
	
	public function getIntegralM($mid,$openid) {
        if(!$mid || !$openid) return array();
		
		$r = DB::fetch_first('select * from %t where mid=%s and openid=%s', array('wx_integral', $mid, $openid));
			
		if(!$r){
			$insert = array();
			$insert['mid'] = $mid;
			$insert['openid'] = $openid;
			$insert['id'] = DB::insert('wx_integral',$insert,true);
			$r = $insert;
		}
		return $r;
    }
	
	public function getIntegralSettingM($mid,$upmemory = 0){
		if(!$mid) return array();
		if(!$upmemory) $r = memory('get','wx-integral_setting-'.$mid);
		if (!$r) {
			$r = DB::fetch_first('select * from %t where mid=%s', array('wx_integral_setting', $mid));
			if($r) memory('set','es-integral_setting-'.$mid,$r);
		}
		return $r;
	}
	
    public function result($openid, $mid) {
        $r = memory('get', $openid . '-' . $mid);
        if (!$r) {
            $r = DB::result_first('select openid from %t where openid=%s and mid=%s limit 1', array('wx_wxuser', $openid, $mid));
            memory('set', $openid . '-' . $mid, $r);
        }
        return $r;
    }

    public function getUid($_mid) {
        $r = memory('get', 'api-uid-' . $_mid);
        if (!$r) {
            DB::SetMainDB(DB_MAIN);
            $r = DB::result_first('select uid from %t where mid=%s', array('wx_apiuser', $_mid));
            memory('set', 'api-uid-' . $_mid, $r);
        }
        return $r;
    }
	public function getApiuserM($mid,$upmemory = 0) {
       // $r = memory('get', 'wx-apiuser-'.$mid);
        //if (!$r) {
            $r = DB::fetch_first('select * from %t where mid=%s limit 1', array('wx_apiuser', $mid));
           // memory('set', 'wx-apiuser-'.$mid, $r);
       // }
        return $r;
    }
    public function getWebSite($mid) {
        //$r = memory('get', 'wx-wxsite-' . $mid);
        if (!$r) {
            DB::SetMainDB(DB_MAIN);
            $r = DB::fetch_first('select * from %t where mid=%s', array('wx_wxsite', $mid));
            memory('set', 'wx-wxsite-' . $mid, $r);
        }
        return $r;
    }

    //返回微会员首页设置模版
    public function getweb($mid) {
        $r = memory('get', 'wxweb-' . $mid);
        if (!$r || (TIME - $r[1] > 3600) || 1) {
            DB::SetMainDB(DB_MAIN);
            $r = DB::result_first('select wxweb from %t where mid=%s limit 1', array('wx_apiuser', $mid));
            $r = array($r, TIME);
            memory('set', 'wxweb-' . $mid, $r);
        }
        return $r[0];
    }
     public function getMid($AppId){
        $r = memory('get', 'wxweb-mid-' . $AppId);
        if (!$r) {
            DB::SetMainDB(DB_MAIN);
            $r = DB::result_first('select mid from %t where AppId=%s limit 1', array('wx_apiuser', $AppId));
            if($r) memory('set', 'wxweb-mid-' . $AppId, $r);
        }
        return $r;
     }

     //返回微会员新闻列表设置模版
    public function get_template_news_list($mid) {
        return DB::result_first('select template_newslist from %t where mid=%s limit 1', array('wx_apiuser', $mid));
    }

    //返回微会员新闻内页设置模版
    public function get_template_news_inside($mid) {
        return DB::result_first('select template_newsinside from %t where mid=%s limit 1', array('wx_apiuser', $mid));
    }

    //返回微会员相册设置模版
    public function get_template_album($mid) {
        return DB::result_first('select template_album from %t where mid=%s limit 1', array('wx_apiuser', $mid));
    }

    //返回微会员会员中心设置模版
    public function get_template_membercenter($mid) {
        return DB::result_first('select template_membercenter from %t where mid=%s limit 1', array('wx_apiuser', $mid));
    }
	
    //收货地址
    public function getAddressList($_mid,$_openid,$memberId=-1){
        //if(!$_mid || !$_openid) return array();
        $where = $this->memberWhere($_openid,$memberId);
        
        $r = DB::fetch_all('select * from %t where mid=%s and status=1 and display=1 %i order by set_default desc', array('common_address',$_mid,$where));
        return $r;
    }
    //读取单条收货地址
    public function getAddressM($_mid,$_openid,$_id,$memberId=-1){
        //if(!$_mid || !$_openid) return array();
        $where = $this->memberWhere($_openid,$memberId);
        
        DB::SetMainDB(DB_MAIN);
        $r = DB::fetch_first('select * from %t where id=%d and mid=%s %i', array('common_address',$_id,$_mid,$where));
        return $r;
    }

    //读取运费模版信息
    public function getFreightM($_mid,$_id){
            //if(!$_mid || !$_openid) return array();
            DB::SetMainDB(3);
            $r = DB::fetch_first('select * from %t where mid=%s and id=%d', array('es_freight',$_mid,$_id));
            return $r;
    }

    //读取运费模版信息
    public function getFreightSetDefault($_mid){
            //if(!$_mid || !$_openid) return array();
            DB::SetMainDB(3);
            $r = DB::fetch_first('select * from %t where mid=%s and display=1 and status=1 order by set_default desc', array('es_freight',$_mid));
            return $r;
    }

    //读取快递信息
    public function getExpressM($_mid,$_id){
            //if(!$_mid || !$_openid) return array();
            DB::SetMainDB(3);
            $r = DB::fetch_first('select * from %t where mid=%s and id=%d', array('es_express',$_mid,$_id));
            return $r;
    }

    //读取配送信息
    public function getshippingM($_mid,$_id){
            //if(!$_mid || !$_openid) return array();
            DB::SetMainDB(3);
            $r = DB::fetch_first('select * from %t where mid=%s and id=%d', array('es_shipping',$_mid,$_id));
            return $r;
    }
    //获取全部地区
    public function getAllRegionList($_upmemory=false){
        if(!$_upmemory) $r = memory('get','getAllRegionList');
        if(!$r){
            $rArr = array();
            $aArr = array();
            $cArr = array();
            DB::SetMainDB(DB_MAIN);
            $r = DB::fetch_all('select `id` as `value`,`title` as `text` from %t where grade=1', array('common_region'));
            DB::SetMainDB(DB_MAIN);
            $citys = DB::fetch_all('select `id` as `value`,`title` as `text`,parentid from %t where grade=2', array('common_region'));
            DB::SetMainDB(DB_MAIN);
            $areas = DB::fetch_all('select `id` as `value`,`title` as `text`,parentid from %t where grade=3', array('common_region'));
            DB::SetMainDB(DB_MAIN);
            $ring = DB::fetch_all('select `id` as `value`,`title` as `text`,`code`,parentid from %t where grade=4', array('common_region_ext'));
            foreach($ring as $rv){
                $rArr[$rv['parentid']][] = $rv;
            }
            foreach($areas as $av){
                $av['children'] = $rArr[$av['value']];
                $aArr[$av['parentid']][] = $av;
            }
            foreach($citys as $cv){
                $cv['children'] = $aArr[$cv['value']];
                $cArr[$cv['parentid']][] = $cv;
            }
            foreach($r as $pk => $pv){
                $r[$pk]['children'] = $cArr[$pv['value']];
            }
//            foreach($areas as $firstK => $firstV){
//                foreach($citys as $secendK => $secendV){
//                    if($firstV['parentid']==$secendV['value']){
//                        $citys[$secendK]['children'][] = $secendV;
//                        break;
//                    }
//                }
//            }
//            foreach($citys as $cKey => $cValue){
//                foreach($r as $pKey => $pValue){
//                    if($cValue['parentid']==$pValue['value']){
//                        $r[$pKey]['children'][] = $cValue;
//                        break;
//                    }
//                }
//            }
            memory('set','getAllRegionList',$r);
        }
//        return array($r,$citys,$areas);
        return $r;
    }
    
    //获取全部地区
    public function getAllRegionListNew($_upmemory=false){
        if(!$_upmemory) $r = memory('get','getAllRegionListNew');
        if(!$r){
            $aArr = array();
            $cArr = array();
            DB::SetMainDB(DB_MAIN);
            $r = DB::fetch_all('select id,`region_code` as `value`,`title` as `text` from %t where grade=1', array('common_region_new'));
            DB::SetMainDB(DB_MAIN);
            $citys = DB::fetch_all('select id,`region_code` as `value`,`title` as `text`,parentid from %t where grade=2', array('common_region_new'));
            DB::SetMainDB(DB_MAIN_READ);
            $areas = DB::fetch_all('select id,`region_code` as `value`,`title` as `text`,parentid from %t where grade=3', array('common_region_new'));
            foreach($areas as $av){
                $aArr[$av['parentid']][] = $av;
            }
            foreach($citys as $cv){
                $cv['children'] = $aArr[$cv['id']];
                $cArr[$cv['parentid']][] = $cv;
            }
            foreach($r as $pk => $pv){
                $r[$pk]['children'] = $cArr[$pv['id']];
            }
            memory('set','getAllRegionListNew',$r);
        }
        return $r;
    }
    //地区列表
    public function getRegionList($_mid,$_pid){
            //if(!$_mid || !$_openid) return array();
            //DB::SetMainDB(3);
            $r = DB::fetch_all('select * from %t where parentid=%d', array('common_region',$_pid));
            return $r;
    }
    //地区列表
    public function getRegionM($_mid,$_id){
            //if(!$_mid || !$_openid) return array();
            //DB::SetMainDB(3);
            $r = DB::fetch_first('select * from %t where id=%d', array('common_region',$_id));
            return $r;
    }
    //订单状态数量
    public function getOrderCount($_mid,$_openid,$type = 'waitPay'){
            //if(!$_mid || !$_openid) return array();
            switch($type){
                    //待付款订单
                    case 'waitingPay':
                            $where = 'and order_status=0 and pay_status=0 and pay_type=1';
                    break;
                    //待发货订单
                    case 'waitingSend':
                            $where = 'and order_status=0 and send_status=0 and ((pay_status=1 and pay_type=1) or pay_type=2)';
                    break;
                    //待收货订单
                    case 'waitingTake':
                            $where = 'and order_status=0 and send_status=1 and ((pay_status=1 and pay_type=1) or pay_type=2)';
                    break;
                    //已完成订单
                    case 'success':
                            $where = 'and order_status=1';
                    break;
            }
            DB::SetMainDB(3);
            $r = DB::result_first('select count(*) from %t where mid=%s and openid=%s %i', array('es_order',$_mid,$_openid,$where));
            return $r;
    }

    //地区列表
    public function getAddressSet($_mid,$uid=0,$_uid=0){
        //if(!$_mid || !$_openid) return array();
        //DB::SetMainDB(3);
        //$r=DB::fetch_first('select is_name,is_phone,is_tel,is_zipcode,is_country,is_province,is_city,is_district,is_area,is_address,is_set_default,is_best_time,id as aid from %t where display=1 and status=1 and mid=%s',array('common_address_setting',$_mid));

        if(!$r){
            $insert = array();
            $insert['mid'] = $_mid;
            $insert['uid'] = $uid;
            $insert['_uid'] = $_uid;
            $insert['inputtime'] = TIME;
            $insert['status'] =1;
            $insert['display'] =1;
            $insert['is_name'] =2;
            $insert['is_phone'] =2;
            $insert['is_tel'] =1;
            $insert['is_zipcode'] =1;
            $insert['is_country'] =2;
            $insert['is_province'] =2;
            $insert['is_city'] =2;
            $insert['is_district'] =2;
            $insert['is_area'] =2;
            $insert['is_address'] =2;
            $insert['is_set_default'] =1;
            $insert['is_best_time'] =1;
            //$insert['aid']=DB::insert('common_address_setting',$insert,true);
            $r=$insert;
        }

        return $r;
    }
    
    //$this->_mid,$this->_openid,$id,$this->_memberId
    public function addressCount($mid='',$openid='',$memberid=''){
        $where = $this->memberWhere($openid,$memberid);
        
        $num = DB::result_first('select count(*) from %t where display=1 and mid=%s %i', array('common_address',$mid,$where));
        
        return $num;
    }

    //$this->_G['clientip']
    function createOpenId($mid,$OpenId='',$clientIp=''){
        if(!$mid || !$OpenId){
            return false;
        }
        DB::SetMainDB(DB_MAIN);
        $memberid = DB::result_first('select id from %t where mid=%s and openid=%s and display=1',array('common_member',$mid,$OpenId));
        if(!$memberid){ // || $_GET['debug']
//            if(!$_GET['debug']) {
//                $insert = array();
//                $insert['inputtime'] = TIME;
//                $insert['status'] = $insert['display'] = 1;
//                $insert['mid'] = $mid;
//                $insert['clientip'] = $clientIp;
//                $insert['openid'] = $OpenId;
//                $memberid = DB::insert('common_member', $insert, true);
//
//            }else{
                $insert = "insert into %t (`mid`,`openid`,`clientip`,`status`,`display`,`inputtime`) select %s,%s,%s,1,1,%d from dual where not exists(select 1 from %t where mid=%s and openid=%s and display=1)";
                $e = DB::query($insert, array('common_member', $mid, $OpenId, $clientIp, TIME,
                    'common_member', $mid, $OpenId
                ));

                DB::SetMainDB(DB_MAIN);
                $memberid = DB::result_first('select id from %t where mid=%s and openid=%s and display=1', array('common_member', $mid, $OpenId));
//                echo 'insert:'.DB::format($insert, array('common_member', $mid, $OpenId, $clientIp, TIME,
//                        'common_member', $mid, $OpenId
//                    ));;
//                echo '<br/>e:'.$e;
//                echo '<br/> memberid:' . $memberid;
//            }
        }
        return $memberid;
    }
    function fetchOpenIdWithMemberId($mid,$memberId=0){
        DB::SetMainDB(DB_MAIN);
        $openid = DB::result_first('select openid from %t where mid=%s and id=%s and display=1',array('common_member',$mid,$memberId));
        return $openid;
    }
    
    //会员条件
    public function memberWhere($_openid='',$memberId=''){
        $thisBool = false; 
        $where = 'and (';
        
        if($memberId && $memberId!=-1){
            $thisBool = true;
            $where .= DB::format('member_id=%d', array($memberId));
        }
        
        if($_openid){
            if($thisBool) $where .= ' or ';
            $thisBool = true;
            $where .= DB::format("openid=%s", array($_openid));
        }
		$where .= ')';
                
        if(!$thisBool){
            $where = '';
        }
        return $where;
    }
    
    //创建微信用户信息
    public function wxuserInsert($data=array()){
        if(!$data || !is_array($data)){
            return false;
        }
        $data['inputtime'] = TIME;
        $data['bind_time'] = TIME;
        DB::SetMainDB(DB_MAIN);
        DB::insert("wx_wxuser", $data);
    }

    //修改微信用户信息
    public function wxuserUpdate($data=array(),$where=""){
        if(!$data || !$where){
            return false;
        }
        
        DB::SetMainDB(DB_MAIN);
        $num = DB::update("wx_wxuser", $data, $where);
        return $num;
    }
    
    //创建会员主表信息
    public function memberInsert($data=array()){
        if(!$data || !is_array($data)){
            return false;
        }
        $data['inputtime'] = TIME;
        $data['bind_time'] = TIME;
        DB::SetMainDB(DB_MAIN);
        $thisId = DB::insert("common_member", $data,true);
        return $thisId;
    }

    //修改会员主表信息
    public function updMember($data=array(),$where=""){
        if(!$data || !$where){
            return false;
        }
        $data['updatetime'] = TIME;
        DB::SetMainDB(DB_MAIN);
        $num = DB::update("common_member", $data, $where);
        return $num;
    }
    
    //修改会员完善表信息
    public function updMemberPerfect($data=array(),$where=""){
        if(!$data || !$where){
            return false;
        }
        $data['updatetime'] = TIME;
        DB::SetMainDB(DB_MAIN);
        $num = DB::update("common_member_perfect", $data, $where);
        return $num;
    }
}

?>